var FormWizard = function () {
    var tree;
    var typetree;
    function initconfirm(){
        $.ajaxSetup({
            async : false
        });
        var languages=affs=flatforms=types="";
        $.post('collectconfig/getUserCofirm', {},function(data) {

            for(var languageindex in data){
                languages += data[languageindex].game_language +" ";
                affs += data[languageindex].game_language + ":" + data[languageindex].game_aff + "<br/>";
                flatforms += data[languageindex].game_language + ":" + data[languageindex].game_platform + "<br/>";
                types += data[languageindex].game_language + ":" + data[languageindex].game_types + "<br/>";
            }

        },"json");
        $("#language_confirm").html(languages);
        $("#affiliations_confirm").html(affs);
        $("#platform_confirm").html(flatforms);
        $("#category_confirm").html(types);
    }

    function  initTypestree(){
        //set ajax sysny
                $.ajaxSetup({
                    async : false
                });
                //set tree
        var setting = { check:{ enable:true},data:    {simpleData:{enable:true}},callback:{ }};
        var zNodes =[
            { id:"1", pId:"0", name:"es", open:false}
        ];
        $.post('collectconfig/getLanguageTypes', {},function(data) {
            zNodes=data;
        },"json");

        $.fn.zTree.init($("#languagetypes"), setting, zNodes);
        typetree = $.fn.zTree.getZTreeObj("languagetypes");


        $("#typestreesubmit").click(function(){
            //check nodes
            var typesCheckedNods = {};
            typetree.getCheckedNodes().forEach(function(e){
                //if pid is not null ,then collect this data

                 if(e.pId){
                     var type_array = e.id.split("_");
                     var language_id =  type_array[0];
                     if(typesCheckedNods[language_id]){
                         typesCheckedNods[language_id].push(type_array[1]);
                     }else{
                         typesCheckedNods[language_id] = new Array();
                         typesCheckedNods[language_id].push(type_array[1]);
                     }
                 }
             });
            $.post('collectconfig/setLanguageTypes', {"datas":typesCheckedNods},function(data) {
                alert("save success");
            },"json");
        });
    }

    return {
        //main function to initiate the module
        initTypeTree:initTypestree,
        initconfirm:initconfirm,
		initformdata:function(){
            $.ajaxSetup({
                async : false
            });
            var affData =  {datas:[{"showName":"bigfish","check":false},{"showName":"alawar","check":true},{"showName":"apple","check":false}]};
            $.post('collectconfig/getUserLanguageConfig', {},function(data) {
                affData = data;
            },"json");

			var chkbox;
		//	var LMdata=[];
		    var affCheckboxs = "";  
			 for(chkbox in affData.datas){
				var checked = "";
					if(affData.datas[chkbox].check){
				      checked  ="checked";	
					  affCheckboxs +="<input type='checkbox' checked ='"+checked+"' name='affchecks'  value='"+
					  affData.datas[chkbox].showName+"'/><span class='help-inline'>"+affData.datas[chkbox].showName+" &nbsp;&nbsp; </span>";
					}else{					
					  affCheckboxs +="<input type='checkbox' name='affchecks' value='"+
					  affData.datas[chkbox].showName+"' /><span class='help-inline'>"+affData.datas[chkbox].showName+" &nbsp;&nbsp; </span>";
					}					
			 }
						$("#inputLM").html(affCheckboxs);
							
				$("#inputLM input[type='checkbox']").bind("click",function(clickEvtObj){
					 if($(clickEvtObj.target).is(":checked")){
                         $.post('collectconfig/setUserLanguageConfig', {"language":$(clickEvtObj.target).val() ,"type":1},function(data) {

                         },"json");

                     }else{
                         $.post('collectconfig/setUserLanguageConfig', {"language":$(clickEvtObj.target).val() ,"type":0},function(data) {

                         },"json");

                     }
				 });
			},
        initPlatformTree:function(){
            //set ajax sysny
            $.ajaxSetup({
                async : false
            });
            //set tree
            var setting = { check:{ enable:true},data:    {simpleData:{enable:true}},callback:{ }};
            var zNodes =[
              { id:"1", pId:"0", name:"es", open:false},
              { id:"2", pId:"1", name:"aa", open:false}
              ];
            $.post('collectconfig/getLanguagePlatform', {},function(data) {
                zNodes=data;
            },"json");

            $.fn.zTree.init($("#languagePlatform"), setting, zNodes);
            tree = $.fn.zTree.getZTreeObj("languagePlatform");
            $("#tree1submit").click(function(){
              //  console.log(tree.getCheckedNodes());
                var checkNodes = {"affs":[],"platforms":[]};
                var languagecheckNodes={};
                tree.getCheckedNodes().forEach(function(e){
                    var tempNode = e.id.split('_');
                    var checkNodestemp ;
                    if(tempNode.length == 3){
                        var languageid = tempNode[0];
                    //    console.log(languagecheckNodes[languageid]);
                        if(languagecheckNodes[languageid]){
                             checkNodestemp=languagecheckNodes[languageid];
                        }else{
                            languagecheckNodes[languageid]={"affs":[],"platforms":[]};;
                            checkNodestemp = languagecheckNodes[languageid];
                        }
                        if(tempNode[1] == 1){
                            checkNodestemp.affs.push(tempNode[2]);
                        }else{
                            checkNodestemp.platforms.push(tempNode[2]);
                        }
                      //  console.log("the id is %s,the type is %s,the value is %s",tempNode[0],tempNode[1],tempNode[2]);
                    }
                });
                console.log(languagecheckNodes);

                $.post('collectconfig/setLanguagePlatform', {"datas":languagecheckNodes},function(data) {
                    alert("save success");
                },"json");
            });

        },
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }

            function format(state) {
                if (!state.id) return state.text; // optgroup
                return "<img class='flag' src='assets/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
            }
            $("#country_list").select2({
                placeholder: "Select",
                allowClear: true,
                formatResult: format,
                formatSelection: format,
                escapeMarkup: function (m) {
                    return m;
                }
            });
            var form = $('#submit_form');
            var error = $('.alert-error', form);
            var success = $('.alert-success', form);
            var displayConfirm = function() {
                $('.display-value', form).each(function(){
                    var input = $('[name="'+$(this).attr("data-display")+'"]', form);
                    if (input.is(":text") || input.is("textarea")) {
                        $(this).html(input.val());
                    } else if (input.is("select")) {
                        $(this).html(input.find('option:selected').text());
                    } else if (input.is(":radio") && input.is(":checked")) {
                        $(this).html(input.attr("data-title"));
                    } else if ($(this).attr("data-display") == 'card_expiry') {
                        $(this).html($('[name="card_expiry_mm"]', form).val() + '/' + $('[name="card_expiry_yyyy"]', form).val());
                    } else if ($(this).attr("data-display") == 'payment') {
                        var payment = [];
                        $('[name="payment[]"]').each(function(){
                            payment.push($(this).attr('data-title'));
                        });
                        $(this).html(payment.join("<br>"));
                    }
                });
            }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
                'nextSelector': '.button-next',
                'previousSelector': '.button-previous',
                onTabClick: function (tab, navigation, index) {
                    return true;
                },
                onNext: function (tab, navigation, index) {
                    success.hide();
                    error.hide();
                    if (form.valid() == false) {
                        return false;
                    }

                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }

                    if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }

                    if (current >= total) {
                        $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').show();
                        displayConfirm();
                    } else {
                        $('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').hide();
                    }
                    App.scrollTo($('.page-title'));
                },
                onPrevious: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }

                    if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }

                    if (current >= total) {
                        $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').show();
                    } else {
                        $('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').hide();
                    }

                    App.scrollTo($('.page-title'));
                },
                onTabShow: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    switch (current){
                        case 2:
                            FormWizard.initPlatformTree();
                            break;
                        case 3:
                            FormWizard.initTypeTree();
                            break;
                        case 4:
                            FormWizard.initconfirm();
                            break;
                    }


                    var $percent = (current / total) * 100;
                    $('#form_wizard_1').find('.bar').css({
                        width: $percent + '%'
                    });
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            $('#form_wizard_1 .button-submit').click(function () {
                alert('Finished! Hope you like it :)');
            }).hide();
        }

    };

}();